package com.tchy.cloud.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by zhongjieyu on 2012/11/03.
 * 文件下载控制层
 */
@Controller
@RequestMapping("/fileDownload")
public class FileDownloadController {


    /**
     *
     *@描述:资源文件下载
     *@return ResponseEntity<?>
     *@作者：zjy
     *@创建日期： 2013年6月16日13:50:22
     */
    @RequestMapping(value = "/download_file")
    public  void download_resource_file(String res_url, HttpServletRequest request,final HttpServletResponse response) {
        try {

            res_url = java.net.URLDecoder.decode(res_url,"UTF-8");

            //获取文件全路径
            String path = request.getSession().getServletContext().getRealPath(res_url);

            File file = new File(path);
            //得到文件名
            String filename = file.getName();
            //如果文件不存在会抛出FileNotFoundException异常，需要捕获后进行处理
            InputStream fis = new BufferedInputStream(new FileInputStream(path));

            byte[] buffer = new byte[fis.available()];

            fis.read(buffer);
            fis.close();

            //清空response
            response.reset();

            String downLoadName = new String(filename.getBytes("gbk"), "iso8859-1");
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

        } catch(FileNotFoundException e){
//			log.error(e.getMessage(), e);

            response.setContentType("text/html");
            try {
                response.getWriter().print("<html><body><h1>该文件不存在或已被移动到其他位置，请联系管理员！谢谢！</h1></body></html>");
            } catch (IOException e1) {
                //log.error(e.getMessage(), e);
            }

        } catch (Exception e) {
            //log.error(e.getMessage(), e);

        }


    }
    }







